﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Portal.BO.Editoral.Category;

using Portal.User.Security;
using Portal.GUI.Users.Common;
using Portal.Core.DAL;


namespace Portal.GUI.EditoralOffice.MainOffce.Category
{
    public partial class CategoryManager : Portal.API.Module
    {
        protected string ParentName = string.Empty;
        string userID = "", assignUser = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            userID = Session["id"] != null ? Session["id"].ToString() : "";
            //người gán

            ViewState["userid"] = assignUser = Page.User.Identity.Name;

            if (!IsPostBack)
            {
                LoadChannel(assignUser);
                ViewState["ParentId"] = 0;
                CategoryHelper.TreebuildAllCat(cboLayout);
                CategoryHelper.TreebuildAllCat_by_ChannelID(ddlParentID, ddlChannel.SelectedValue.ToString());
                cboLayout.Items[0].Text = string.Empty;
                //bindData();
            }
        }

        #region Load Channel
        private void LoadChannel(string userID)
        {
            MainSecurity ms = new MainSecurity();
            if (userID != Const.Global_Admin && userID != Const.TONG_BIEN_TAP)
            {
                ddlChannel.DataSource = ms.GetChannelAsTable(userID);
                ddlChannel.DataBind();
                BindCatListbyUserID(userID);
                ddlChannel.Enabled = false;
            }
            else
            {
                using (Xmobile.Users.MainDB db = new Xmobile.Users.MainDB())
                {
                    //ddlChannel.DataSource = db.ChannelCollection.GetAllAsDataTable();
                    ddlChannel.DataSource = db.StoreProcedure.vc_Execute_Sql("SELECT * FROM Channel");
                    ddlChannel.DataBind();
                    BindListCatbyChannelID(ddlChannel.SelectedValue.Trim());
                }
            }

        }
        #endregion

        private void BindCatListbyUserID(string userid)
        {
            DataTable dt = new DataTable();
            dt = CategoryHelper.GetCategoryParentByUserID(userid);
            grvCategories.DataSource = dt;
            grvCategories.DataBind();
        }


        private void BindListCatbyChannelName(string channel_name)
        {
            DataTable dt = new DataTable();
            dt = CategoryHelper.GetCategoryParentByChannelName(channel_name);
            grvCategories.DataSource = dt;
            grvCategories.DataBind();
        }

        private void BindListCatbyChannelID(string id)
        {
            DataTable dt = new DataTable();
            dt = CategoryHelper.GetCategoryParentByChannelID(id);
            grvCategories.DataSource = dt;
            grvCategories.DataBind();
        }

        private void bindData()
        {
            grvCategories.DataSource = CategoryHelper.GetCategoriesByParent((int)ViewState["ParentId"]);
            grvCategories.DataBind();
        }

        protected void grvCategories_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvCategories.EditIndex = -1;
            bindData();
        }

        protected void grvCategories_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow editRow = grvCategories.Rows[grvCategories.EditIndex];
            CategoryRow category = CategoryHelper.getCatInfoAsCategoryRow((int)grvCategories.DataKeys[grvCategories.EditIndex].Value);
            category.Cat_Name = (editRow.FindControl("txtCatName") as TextBox).Text;
            category.Cat_Order = int.Parse((editRow.FindControl("txtCatOrder") as TextBox).Text);
            category.Cat_isHidden = (editRow.FindControl("chkIsHidden") as CheckBox).Checked;
            category.Cat_DisplayURL = (editRow.FindControl("txtCatDisplayURL") as TextBox).Text;
            category.Cat_ParentID = int.Parse((editRow.FindControl("cboParentCat") as DropDownList).SelectedValue);
            //category.Channel_ID = int.Parse()
            CategoryHelper.UpdateCategoryRow(category);
            grvCategories.EditIndex = -1;
            bindData();
        }

        protected void grvCategories_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            CategoryHelper.Delete((int)(grvCategories.DataKeys[e.RowIndex].Value));
            bindData();
        }

        protected void grvCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            ParentName = (grvCategories.SelectedRow.FindControl("btnCatName") as LinkButton).Text;
            lblParentCatName.Text = "Chuyên mục hiện tại: " + ParentName;
            ViewState["ParentId"] = grvCategories.DataKeys[grvCategories.SelectedIndex].Value;
            ddlParentID.SelectedValue = ViewState["ParentId"].ToString();
            grvCategories.EditIndex = -1;
            grvCategories.SelectedIndex = -1;
            bindData();
            btnGoToRoot.Visible = true;
        }

        protected void grvCategories_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((bool)(e.Row.DataItem as DataRowView)["Cat_isHidden"]) e.Row.CssClass = "highLight";
            }
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList cboParentCat = e.Row.FindControl("cboParentCat") as DropDownList;
                CategoryHelper.TreebuildAllCat(cboParentCat);
                cboParentCat.Items[0].Text = string.Empty;
                cboParentCat.Items[0].Value = "0";
                try
                {
                    cboParentCat.SelectedValue = ((DataRowView)e.Row.DataItem)["Cat_ParentID"].ToString();
                }
                catch { }
            }
        }

        protected void grvCategories_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grvCategories.EditIndex = e.NewEditIndex;
            bindData();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            /*
            CategoryHelper.CreateCat2(
                txtCatName.Text,
                int.Parse(txtCatOrder.Text),
                string.Empty,
                txtCatDisplayURL.Text,
                (int)ViewState["ParentId"],
                int.Parse(cboEditionType.SelectedValue),
                string.Empty,
                false,
                false,
                cboLayout.SelectedIndex == 0 ? string.Empty : CategoryHelper.GetTabReferenceByCatId(int.Parse(cboLayout.SelectedValue)));
            */

            CategoryHelper.CreateNewCat(
                txtCatName.Text,
                int.Parse(txtCatOrder.Text),
                string.Empty,
                txtCatDisplayURL.Text,
               Convert.ToInt32(ddlParentID.SelectedValue),
                int.Parse(cboEditionType.SelectedValue),
                txtIcon.Text.Trim(),
                false,
                Convert.ToBoolean(chkDisplay.Checked),
                cboLayout.SelectedIndex == 0 ? string.Empty : CategoryHelper.GetTabReferenceByCatId(int.Parse(cboLayout.SelectedValue)), Convert.ToInt32(ddlChannel.SelectedValue));


            // reset form
            txtCatDisplayURL.Text = string.Empty;
            txtCatName.Text = string.Empty;
            txtCatOrder.Text = string.Empty;

            grvCategories.EditIndex = -1;
            //bindData();
            BindListCatbyChannelID(ddlChannel.SelectedValue);
            //xoa cache category
            string cacheName = "TreebuildAllCat_by_Channel_" + HttpContext.Current.User.Identity.Name + "_" + ddlChannel.SelectedValue;
            HttpContext.Current.Cache.Remove(cacheName);
            HttpContext.Current.Cache.Remove(cacheName + "_strResult");

            CategoryHelper.TreebuildAllCat_by_ChannelID(ddlParentID, ddlChannel.SelectedValue.ToString());
            UpdatePanel1.Update();
        }

        protected void btnGoToRoot_Click(object sender, EventArgs e)
        {
            lblParentCatName.Text = string.Empty;
            ViewState["ParentId"] = 0;
            grvCategories.EditIndex = -1;
            grvCategories.SelectedIndex = -1;
            //bindData();
            LoadChannel(assignUser);
            btnGoToRoot.Visible = false;
        }

        protected void txtCatName_TextChanged(object sender, EventArgs e)
        {
            txtCatDisplayURL.Text = BO.UnicodeUtility.UnicodeToKoDauAndGach(txtCatName.Text).ToLower();
        }

        protected void ddlChannel_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindListCatbyChannelID(ddlChannel.SelectedValue.Trim());
            CategoryHelper.TreebuildAllCat_by_ChannelID(ddlParentID, ddlChannel.SelectedValue.ToString());
        }

       
    }
   
}